package org.csu.petstore_manage.service;

import org.csu.petstore_manage.domain.Account;
import org.csu.petstore_manage.persistence.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Properties;
import java.util.Random;


@Service
public class AccountService {
    @Autowired
    private AccountMapper accountMapper;

    public Account getAccount(String username){
        return accountMapper.getAccountByUsername(username);
    }

    public Account getAccount(String username, String password){
        Account account = new Account();
        account.setUsername(username);
        account.setPassword(password);
        return accountMapper.getAccountByUsernameAndPassword(account);
    }
    public void insertAccount(Account account) {
        accountMapper.insertAccount(account);
         System.out.println("insert account");
    }
    public String findPassWord(String email) throws MessagingException {
      //  accountMapper.insertAccount(account);
       // System.out.println("insert account");
        String  authcode=accountMapper.findPassword(email);
        Properties properties = new Properties();
        properties.setProperty("mail.transport.protocol", "smtp");//发送邮件协议
        properties.setProperty("mail.smtp.auth", "true");//需要验证
        properties.setProperty("mail.debug", "true");//设置debug模式 后台输出邮件发送的过程
        Session session = Session.getInstance(properties);
        session.setDebug(true);//debug模式
        System.out.println(email+"1"+authcode);
        //邮件信息
        Message messgae = new MimeMessage(session);
        messgae.setFrom(new InternetAddress("1183764949@qq.com"));//设置发送人
        messgae.setText("Authcode:" + authcode + ". JPetStore All Right Reserved.");//设置邮件内容
        messgae.setSubject("Mail Authentication");//设置邮件主题
        //发送邮件
        Transport tran = session.getTransport();
//        tran.connect("smtp.office365.com", 587, "Anarhyroch@outlook.com", "szhnwuisudwknfsu");//连接到新浪邮箱服务器
        tran.connect("smtp.qq.com",587, "1183764949@qq.com", "rwahibhkqkmihfdf");//连接到QQ邮箱服务器
        tran.sendMessage(messgae, new Address[]{ new InternetAddress(email)});//设置邮件接收人
        tran.close();
        return authcode;
    }

    }

